package sorter;

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.rmi.Naming;
import java.util.Observable;

@SuppressWarnings("unchecked")
public class SorterThread extends Observable implements Runnable
{
	private Thread thread;
	private Comparable[] C;
	private int ThreadNumber;
	private Comparable[] result;
	private String HOST;
	
	/**
	 * Constructor of the class SorterThread
	 * @param TN
	 * @param c
	 * @param LJ
	 */
	public SorterThread(int TN, Comparable[] c, ListJoiner LJ)
	{
		C = c;
		ThreadNumber = TN;
		addObserver(LJ);
		HOST = "localhost";
	}
	
	/**
	 * Function that calls for a sorter on the rmi server
	 * @param c
	 * @throws Exception
	 */
	public void sort(Comparable[] c) throws Exception
	{
		ISortFactory fact = (ISortFactory) Naming.lookup("rmi://" + HOST + "/factory");
		ISorter sorter = fact.createSorter();
		result = sorter.sort(c);
		setChanged();
		notifyObservers();
	}
	
	/**
	 * Function to return the sorted list
	 * @return
	 */
	public Comparable[] getList()
	{
		return result;
	}
	
	/**
	 * Start Function of the thread
	 * Makes a new thread, calls for stopping after done(setDeamon) and starts the funtion Run()
	 */
	 public void start() 
	 {
		    thread = new Thread(this);
		    thread.setDaemon(true);
		    thread.start();
		    
	}
	 
	 /**
	  * Function to call the sort function
	  */
	@Override
	public void run() 
	{
	 try {
		sort(C);
	} catch (Exception e) {
		// TODO Auto-generated catch block
		e.printStackTrace();
	}	
	}
	
	/**
	 * Function to return the ThreadNumber
	 * @return
	 */
	public int getThreadNumber()
	{
		return ThreadNumber;
	}
	
}
